<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>意见反馈 - 通用反馈系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            background: #f5f5f5;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .feedback-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .feedback-form {
            background: #fff;
            border-radius: 8px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #1890ff;
        }
        
        .form-group textarea {
            height: 120px;
            resize: vertical;
        }
        
        .form-group .required {
            color: #ff4d4f;
        }
        
        .submit-section {
            text-align: center;
            margin-top: 30px;
        }
        
        .btn-submit {
            background: #1890ff;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
            transition: background-color 0.3s ease;
        }
        
        .btn-submit:hover {
            background: #40a9ff;
        }
        
        .btn-submit:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .btn-cancel {
            background: #f5f5f5;
            color: #666;
            border: 1px solid #d9d9d9;
            padding: 12px 30px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        
        .btn-cancel:hover {
            background: #e6f7ff;
            border-color: #91d5ff;
        }
        
        .status-message {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 20px;
            display: none;
        }
        
        .status-success {
            background: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }
        
        .status-error {
            background: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
        
        .help-text {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }
        
        .feedback-header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .feedback-header h1 {
            color: #333;
            margin-bottom: 10px;
        }
        
        .feedback-header p {
            color: #666;
            margin: 0;
        }

        .char-count {
            text-align: right;
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }

        .char-count.warning {
            color: #ff9800;
        }

        .char-count.error {
            color: #f44336;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .feedback-container {
                padding: 10px;
            }
            
            .feedback-form {
                padding: 20px;
            }
            
            .submit-section {
                display: flex;
                flex-direction: column;
                gap: 10px;
            }
            
            .btn-submit,
            .btn-cancel {
                margin: 0;
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="feedback-container">
        <div class="feedback-header">
            <h1>💬 意见反馈</h1>
            <p>您的建议和反馈对我们非常重要，我们会认真对待每一条反馈</p>
        </div>
        
        <div class="feedback-form">
            <div id="statusMessage" class="status-message"></div>
            <input type="hidden" id="shopName" value="<?php echo isset($shopName) ? htmlspecialchars($shopName) : ''; ?>">
            
            <form id="feedbackForm">
                <div class="form-group">
                    <label for="account">用户名 <span class="required">*</span></label>
                    <input type="text" id="account" name="account" required>
                    <div class="help-text">请输入您的用户名或邮箱</div>
                </div>
                
                <div class="form-group">
                    <label for="action">反馈类型 <span class="required">*</span></label>
                    <select id="action" name="action" required>
                        <option value="">请选择反馈类型</option>
                        <option value="问题反馈">问题反馈</option>
                        <option value="功能建议">功能建议</option>
                        <option value="体验优化">体验优化</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="content">详细描述 <span class="required">*</span></label>
                    <textarea id="content" name="content" placeholder="请详细描述您遇到的问题、建议或想法..." required></textarea>
                    <div class="help-text">请尽可能详细地描述，这样我们能够更好地理解和解决问题</div>
                    <div id="charCount" class="char-count">0/1000</div>
                </div>
               
                <div class="submit-section">
                    <button type="submit" class="btn-submit" id="submitBtn">提交反馈</button>
                    <button type="button" class="btn-cancel" id="cancelBtn">取消</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 反馈页面JavaScript
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('feedbackForm');
            const submitBtn = document.getElementById('submitBtn');
            const cancelBtn = document.getElementById('cancelBtn');
            const statusMessage = document.getElementById('statusMessage');
            const accountInput = document.getElementById('account');
            const contentTextarea = document.getElementById('content');
            const charCount = document.getElementById('charCount');
            
            // 设置用户名
            const shopName = document.getElementById('shopName').value;
            if(shopName){
                accountInput.value = shopName;
            }
            
            // 字符计数功能
            function updateCharCount() {
                const length = contentTextarea.value.length;
                charCount.textContent = `${length}/1000`;
                
                if (length > 1000) {
                    charCount.className = 'char-count error';
                } else if (length > 800) {
                    charCount.className = 'char-count warning';
                } else {
                    charCount.className = 'char-count';
                }
            }
            
            contentTextarea.addEventListener('input', updateCharCount);
            
            // 绑定事件
            form.addEventListener('submit', handleSubmit);
            cancelBtn.addEventListener('click', handleCancel);
            
            // 处理表单提交
            async function handleSubmit(e) {
                e.preventDefault();
                
                // 验证表单
                if (!validateForm()) {
                    return;
                }
                
                // 禁用提交按钮
                submitBtn.disabled = true;
                submitBtn.textContent = '提交中...';
                
                try {
                    // 收集表单数据
                    const formData = new FormData(form);
                    const feedbackData = {
                        account: formData.get('account'),
                        action: formData.get('action'),
                        content: formData.get('content'),
                        timestamp: new Date().toISOString(),
                        userAgent: navigator.userAgent,
                        url: window.location.href
                    };
                    
                    // 模拟提交到服务器
                    const result = await submitFeedback(feedbackData);
                    
                    if (result.success) {
                        showMessage('反馈提交成功！感谢您的建议，我们会认真处理。', 'success');
                        // 只清空反馈类型和详细描述，保留用户名
                        document.getElementById('action').value = '';
                        document.getElementById('content').value = '';
                        updateCharCount();
                    } else {
                        throw new Error(result.message || '提交失败，请重试');
                    }
                    
                } catch (error) {
                    console.error('提交反馈失败:', error);
                    showMessage('提交失败：' + error.message, 'error');
                } finally {
                    // 恢复提交按钮
                    submitBtn.disabled = false;
                    submitBtn.textContent = '提交反馈';
                }
            }
            
            // 提交反馈到API
            function submitFeedback(data) {
                return new Promise((resolve, reject) => {
                    // 准备提交的数据
                    const submitData = {
                        account: data.account,
                        action: data.action,
                        content: data.content,
                        timestamp: data.timestamp,
                        userAgent: data.userAgent,
                        url: data.url
                    };
                    
                    // 发送POST请求到后端代理接口
                    console.log('提交数据到后端代理:', submitData);
                    const apiUrl = window.location.pathname.replace('/suggest', '/submit_feedback');
                    console.log('API URL:', apiUrl);
                    fetch(apiUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(submitData)
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP错误: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(result => {
                        console.log('API响应:', result);
                        
                        // 检查返回的code字段
                        if (result.code === '0000') {
                            resolve({
                                success: true,
                                message: result.message || '反馈提交成功'
                            });
                        } else {
                            reject(new Error(result.message || '提交失败，请重试'));
                        }
                    })
                    .catch(error => {
                        console.error('API调用失败:', error);
                        console.error('错误详情:', {
                            message: error.message,
                            stack: error.stack,
                            url: apiUrl
                        });
                        reject(new Error('网络错误，请检查网络连接后重试'));
                    });
                });
            }
            
            // 显示状态消息
            function showMessage(message, type) {
                statusMessage.textContent = message;
                statusMessage.className = `status-message status-${type}`;
                statusMessage.style.display = 'block';
                
                // 3秒后自动隐藏成功消息
                if (type === 'success') {
                    setTimeout(() => {
                        statusMessage.style.display = 'none';
                    }, 3000);
                }
            }
            
            // 处理取消按钮
            function handleCancel() {
                if (confirm('确定要取消吗？未保存的内容将丢失。')) {
                    // 关闭当前标签页或返回上一页
                    if (window.history.length > 1) {
                        window.history.back();
                    } else {
                        window.close();
                    }
                }
            }
            
            // 表单验证
            function validateForm() {
                const requiredFields = ['account', 'action', 'content'];
                let isValid = true;
                
                requiredFields.forEach(fieldName => {
                    const field = document.getElementById(fieldName);
                    if (!field.value.trim()) {
                        field.style.borderColor = '#ff4d4f';
                        isValid = false;
                    } else {
                        field.style.borderColor = '#d9d9d9';
                    }
                });
                
                // 检查内容长度
                if (contentTextarea.value.length > 1000) {
                    contentTextarea.style.borderColor = '#ff4d4f';
                    showMessage('详细描述不能超过1000个字符', 'error');
                    isValid = false;
                }
                
                return isValid;
            }
            
            // 实时验证
            const requiredFields = ['account', 'action', 'content'];
            requiredFields.forEach(fieldName => {
                const field = document.getElementById(fieldName);
                field.addEventListener('blur', function() {
                    if (this.value.trim()) {
                        this.style.borderColor = '#52c41a';
                    } else {
                        this.style.borderColor = '#ff4d4f';
                    }
                });
                
                field.addEventListener('input', function() {
                    if (this.value.trim()) {
                        this.style.borderColor = '#d9d9d9';
                    }
                });
            });
            
            // 初始化字符计数
            updateCharCount();
        });
    </script>
</body>
</html>
